package com.dsg.controller.approve;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.toolbox.DateUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.apply.DsgApplyBill;
import com.dsg.entity.approve.DsgApproveCase;
import com.dsg.entity.dto.FrontPageDto;
import com.dsg.service.apply.IDsgApplyBillService;
import com.dsg.service.approve.IDsgApproveCaseService;
import com.dsg.workflow.AbstractWorkflowService;
import com.dsg.workflow.WorkflowEngine;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 實例動態表 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-04
 */
@RestController
@RequestMapping("/approve/dsgApproveCase")
@Slf4j
@Api(description = "實例動態表")
public class DsgApproveCaseController extends BaseController {

    @Autowired
    WorkflowEngine engine;
    @Autowired
    IDsgApplyBillService billService;
    @Autowired
    IDsgApproveCaseService caseService;

    @GetMapping(value = "/countTask")
    @ApiOperation("首頁")
    @ApiResponses({
            @ApiResponse(response = FrontPageDto.class, code = 1, message = "ok")
    })
    public AjaxResult countTask() {
        List<DsgApproveCase> caseList = caseService.getTaskList(getUserId());

        FrontPageDto dto = new FrontPageDto();
        List<DsgApproveCase> list = caseList.stream().filter(e -> e.getStatus() == DsgApproveCase.Status.started.getCode()).collect(Collectors.toList());
        dto.setTodo(list.size());

        Date sevenDaysBefore = DateUtil.addDays(new Date(), -7);
        list = caseList.stream().filter(e -> e.getUpdateTime().after(sevenDaysBefore) &&
                e.getStatus() == DsgApproveCase.Status.approved.getCode()).collect(Collectors.toList());
        dto.setLastSeven(list.size());

        Date oneMonthBefore = DateUtil.addMonths(new Date(), -1);
        list = caseList.stream().filter(e -> e.getUpdateTime().after(oneMonthBefore) &&
                e.getStatus() == DsgApproveCase.Status.approved.getCode()).collect(Collectors.toList());
        dto.setLastMonth(list.size());

        list = caseList.stream().filter(e -> AbstractWorkflowService.NODE_CS_WAITING_LIST.equals(e.getTaskName()) &&
                e.getStatus() == DsgApproveCase.Status.started.getCode())
                .collect(Collectors.toList());
        dto.setCsWaitingList(list.size());

        list = caseList.stream().filter(e -> AbstractWorkflowService.NODE_SUP_APPROVE.equals(e.getTaskName()) &&
                e.getStatus() == DsgApproveCase.Status.started.getCode())
                .collect(Collectors.toList());
        dto.setSupApprove(list.size());

        list = caseList.stream().filter(e -> AbstractWorkflowService.NODE_CHECK_LIST.equals(e.getTaskName()) &&
                e.getStatus() == DsgApproveCase.Status.started.getCode())
                .collect(Collectors.toList());
        dto.setCheckList(list.size());

        return success(dto);
    }

    @GetMapping(value = "/begin")
    @ApiOperation("begin")
    public AjaxResult begin(String billOid) throws Exception {
        DsgApplyBill applyBill = billService.getById(billOid);
        engine.begin(applyBill);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    @GetMapping(value = "/forward")
    @ApiOperation("forward")
    public AjaxResult forward(String caseOid) throws Exception {
        DsgApproveCase approveCase = caseService.getById(caseOid);
        engine.forward(approveCase);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    @GetMapping(value = "/backward")
    @ApiOperation("backward")
    public AjaxResult backward(String caseOid) throws Exception {
        DsgApproveCase approveCase = caseService.getById(caseOid);
        engine.backward(approveCase);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 查询列表（分页）
     *
     * @param dsgApproveCase
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("查询列表（分页）")
    public AjaxResult list(DsgApproveCase dsgApproveCase) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("CREATE_TIME");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        dsgApproveCase.setEntCode(SingletonLoginUtils.getSystemEntCode());
        page = caseService.selectByList(page, dsgApproveCase);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, page.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

}
